import 'package:FineArt/core/api/class_api.dart';
import 'package:FineArt/core/api/course_api.dart';
import 'package:FineArt/core/api/module_api.dart';
import 'package:FineArt/core/api/resource_api.dart';
import 'package:FineArt/core/utils/toast.dart';
import 'package:FineArt/utils/log_util.dart';
import 'package:FineArt/utils/platform_util.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_swiper/flutter_swiper.dart';

import 'RoundCheckBox.dart';

import 'package:FineArt/core/model/class_entity.dart';
import 'package:FineArt/core/model/student_entity.dart';

class ImageViewPage extends StatefulWidget {
  // ignore: non_constant_identifier_names
  static void JumpToImagePreview(Resource resource, var context) {
    Navigator.of(context).push(MaterialPageRoute(builder: (context) {
      return ImageViewPage(resource, null, null);
    }));
  }

  static void JumpToImageView1(
      String mediumImage, String largeImage, var context) {
    Navigator.of(context).push(MaterialPageRoute(builder: (context) {
      return ImageViewPage(null, mediumImage, largeImage);
    }));
  }

  Resource resource = null;
  String mediumImage = null;
  String largeImage = null;

  ImageViewPage(this.resource, this.mediumImage, this.largeImage);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new _ImageViewPageState();
  }
}

class _ImageViewPageState extends State<ImageViewPage> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    getMediumImage();
    getClasses();
  }

  var width;
  bool isCheck = false;
  List<ClassEntity> clList = new List();
  List<StudentEntity> stuList = new List();

  String largeImageUrl = "";
  CachedNetworkImage cnimage = null;

  Map class_student_map = new Map(); //班级-学生的map

  void getClasses() {
    ClassApi().classList().then((res) {
      if (res.code == 200) {
        setState(() {
          clList.clear();
          for (Class c in res.data) {
            ClassEntity entity = new ClassEntity(c.classname, c.classid);
            clList.add(entity);
          }

          if (clList.length > 0) {
            ClassEntity entity = clList[0];
            entity.isCheck = true;
            //请求学生列表
            ClassApi().studentList(entity.id).then((res) {
              if (res.code == 200) {
                List<StudentEntity> ss = [];
                ss.add(StudentEntity("全部", 0, true));
                for (Student s in res.data) {
                  StudentEntity e = new StudentEntity(s.name, s.uid, false);
                  ss.add(e);
                }
                class_student_map[entity.id] = ss;
                setState(() {
                  stuList = ss;
                });
              }
            });
          }
        });
      }
    });
  }

  void getMediumImage() {
    double height = MediaQuery.of(context).size.height;

    if (widget.resource != null) {
      ResourceApi()
          .resourceDetail(widget.resource.id, widget.resource.type)
          .then((res) {
        if (res.code == 200) {
          if (res.data.type == 1) //图片
          {
            ResourceInfo1 info = res.data.info;
            String url = "";

            if (info.url.isEmpty) {
              url = info.sdurl;
              largeImageUrl = info.hdurl;
            } else {
              url = info.url + "_m" + info.ext;
              largeImageUrl = info.url + "" + info.ext;
            }

            setState(() {
              cnimage = CachedNetworkImage(
                imageUrl: url,
                placeholder: (context, url) => CircularProgressIndicator(),
                errorWidget: (context, url, error) => Icon(Icons.error),
              );
            });
          }
        }
      });
    } else if (widget.mediumImage != null && widget.largeImage != null) {
      largeImageUrl = widget.largeImage;
      setState(() {
        cnimage = CachedNetworkImage(
          imageUrl: widget.mediumImage,
          placeholder: (context, url) => CircularProgressIndicator(),
          errorWidget: (context, url, error) => Icon(Icons.error),
        );
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    // SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.bottom]);
    //显示底部栏(隐藏顶部状态栏)
//    SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.bottom]);
    //显示顶部栏(隐藏底部栏)
//    SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.top]);
    //隐藏底部栏和顶部状态栏
    // SystemChrome.setEnabledSystemUIOverlays([]);
    width = MediaQuery.of(context).size.width;
    var height = MediaQuery.of(context).size.height;
    // clList = _buildClassList();

    double item_space = 26;

    return Scaffold(
        backgroundColor: Colors.black,
        body: Container(
          height: height,
          child: SafeArea(
            child: Stack(
              children: [
                Center(child: cnimage),
                Positioned(
                    top: 10,
                    left: 5,
                    child: InkWell(
                      child: Image.asset("assets/images/arrow_back_white.png"),
                      onTap: () {
                        Navigator.of(context).pop(this);
                      },
                    )),
                Positioned(
                    bottom: 0,
                    child: Container(
                      width: width,
                      color: Colors.white,
                      padding: EdgeInsets.fromLTRB(16, 5, 10, 5),
                      child: Row(
                        children: [
                          Row(
                            children: [
                              InkWell(
                                onTap: () {
                                  // ToastUtils.toast("高清");
                                  PlatformUtil.showHdImage(largeImageUrl);
                                },
                                child: Column(
                                  children: [
                                    Image.asset(
                                      "assets/images/icon_highlight.png",
                                      width: 20,
                                      height: 16,
                                    ),
                                    Text(
                                      "高清",
                                      style: TextStyle(
                                          fontSize: 14, color: Colors.black),
                                    )
                                  ],
                                ),
                              ),
                              SizedBox(
                                width: item_space,
                              ),
                            ],
                          ),
                          Row(
                            children: [
                              InkWell(
                                onTap: () {
                                  ToastUtils.toast("收藏");
                                },
                                child: Column(
                                  children: [
                                    Image.asset(
                                      "assets/images/icon_fivorite.png",
                                      width: 20,
                                      height: 16,
                                    ),
                                    Text(
                                      "收藏",
                                      style: TextStyle(
                                          fontSize: 14, color: Colors.black),
                                    )
                                  ],
                                ),
                              ),
                              SizedBox(
                                width: item_space,
                              ),
                            ],
                          ),
                          if (widget.resource != null)
                            Row(
                              children: [
                                InkWell(
                                  onTap: () {
                                    showBottomModel(true);
                                  },
                                  child: Column(
                                    children: [
                                      Image.asset(
                                        "assets/images/icon_jiangjie.png",
                                        width: 20,
                                        height: 16,
                                      ),
                                      Text(
                                        "讲解",
                                        style: TextStyle(
                                            fontSize: 14, color: Colors.black),
                                      )
                                    ],
                                  ),
                                ),
                                SizedBox(
                                  width: item_space,
                                ),
                              ],
                            ),
                          if (false)InkWell(
                            onTap: () {
                              ToastUtils.toast("带画");
                            },
                            child: Column(
                              children: [
                                Image.asset(
                                  "assets/images/icon_daihua.png",
                                  width: 20,
                                  height: 16,
                                ),
                                Text(
                                  "带画",
                                  style: TextStyle(
                                      fontSize: 14, color: Colors.black),
                                )
                              ],
                            ),
                          ),
                          if (widget.resource != null)
                            Expanded(
                                child: Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: [
                                buildRoundText("投送", () {
                                  showBottomModel(false);
                                }, Colors.white, Colors.red)
                              ],
                            ))
                        ],
                      ),
                    ))
              ],
            ),
          ),
        ));
  }

  Widget buildRoundText(
      String text, Function press, Color color, Color bgColor) {
    return InkWell(
      onTap: press,
      child: Container(
        decoration: BoxDecoration(
            color: bgColor,
            borderRadius: BorderRadius.all(Radius.circular(25))),
        padding: EdgeInsets.symmetric(vertical: 10, horizontal: 40),
        child: Text(
          text,
          style: TextStyle(color: color, fontSize: 16),
        ),
      ),
    );
  }

  void startShare() {
    if (clList.isEmpty || stuList.isEmpty) {
      ToastUtils.error("获取班级或学生信息错误");
      return;
    }

    int classId = -1;
    for (ClassEntity c in clList) {
      if (c.isCheck) {
        classId = c.id;
        break;
      }
    }

    if (classId == -1) {
      ToastUtils.error("请选择班级和学生");
      return;
    }

    List<String> members = [];
    for (StudentEntity s in stuList) {
      if (!s.isAll && s.isCheck) {
        members.add(s.id.toString());
      }
    }
    if (members.isEmpty) {
      ToastUtils.error("请选择班级和学生");
      return;
    }

    Resource resource = widget.resource;

    ShareBody shareBody = new ShareBody(
        resid: resource.id,
        type: resource.type,
        url: resource.url,
        title: resource.title,
        uids: members);
    ResourceApi().share(shareBody).then((res) {
      if (res.code == 200) {
        ToastUtils.success(res.msg);
      } else {
        ToastUtils.error(res.msg);
      }
    });
  }

  void startCourse() {
    if (largeImageUrl != null && largeImageUrl.isNotEmpty) {
      if (clList.isEmpty || stuList.isEmpty) {
        ToastUtils.error("获取班级或学生信息错误");
        return;
      }

      int classId = -1;
      for (ClassEntity c in clList) {
        if (c.isCheck) {
          classId = c.id;
          break;
        }
      }

      if (classId == -1) {
        ToastUtils.error("请选择班级和学生");
        return;
      }

      List<String> members = [];
      for (StudentEntity s in stuList) {
        if (!s.isAll && s.isCheck) {
          members.add(s.id.toString());
        }
      }
      if (members.isEmpty) {
        ToastUtils.error("请选择班级和学生");
        return;
      }

      CourseBody course =
          CourseBody(members: members, id: widget.resource.id, layout: 0);
      ClassApi().createCourse(classId, course).then((res) {
        if (res.code == 200) {
          PlatformUtil.startCourse(largeImageUrl, res.data.courseid);
        } else {
          ToastUtils.error(res.msg);
        }
      });
    } else {
      ToastUtils.error("资源错误");
    }
  }

  void showBottomModel(bool isCasting) {
    showModalBottomSheet(
        context: context,
        isScrollControlled: false,
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(10), topRight: Radius.circular(10))),
        builder: (BuildContext context) {
          return StatefulBuilder(
              builder: (BuildContext context, StateSetter setState) {
            return _buildBottomContainer(setState, isCasting);
          });
        });
  }

  Widget _buildClassItem(int index, Function setState) {
    ClassEntity entity = clList[index];
    return Padding(
        padding: EdgeInsets.only(
          left: 10,
        ),
        child: Row(mainAxisAlignment: MainAxisAlignment.start, children: [
          RoundCheckBox(
              value: entity.isCheck,
              isRadio: true,
              onChanged: (bool val) {
                LogUtil.d("is Check $index $val");
                if (clList[index].isCheck) // radio效果，选中的时候再点击，
                {
                  setState(() {
                    clList[index].isCheck = true;
                  });

                  return;
                }
                if (val) {
                  setState(() {
                    for (int i = 0; i < clList.length; i++) {
                      bool check = i == index ? true : false;
                      clList[i].isCheck = check;
                    }
                  });
                } else {
                  setState(() {
                    clList[index].isCheck = val;
                  });
                }

                //如果学生列表存在
                if (class_student_map.containsKey(entity.id)) {
                  setState(() {
                    stuList = class_student_map[entity.id];
                  });
                } else {
                  //请求学生列表
                  ClassApi().studentList(entity.id).then((res) {
                    if (res.code == 200) {
                      List<StudentEntity> ss = [];
                      ss.add(StudentEntity("全部", 0, true));
                      for (Student s in res.data) {
                        StudentEntity e =
                            new StudentEntity(s.name, s.uid, false);
                        ss.add(e);
                      }
                      class_student_map[entity.id] = ss;
                      setState(() {
                        stuList = ss;
                      });
                    }
                  });
                }
              }),
          Text(entity.name)
        ]));
  }

  Widget _buildStuItem(int index, Function setState) {
    return Padding(
        padding: EdgeInsets.only(
          left: 10,
        ),
        child: Row(mainAxisAlignment: MainAxisAlignment.start, children: [
          RoundCheckBox(
              value: stuList[index].isCheck,
              onChanged: (bool val) {
                LogUtil.d("is Check $index $val");
                if (index == 0) {
                  for (int i = 0; i < stuList.length; i++) {
                    setState(() {
                      stuList[i].isCheck = val;
                    });
                  }
                } else {
                  setState(() {
                    stuList[index].isCheck = val;
                  });
                }
              }),
          Text(stuList[index].name)
        ]));
  }

  Widget _buildBottomContainer(Function setState, bool isCasting) {
    return Container(
      height: 400, //对话框高度就是此高度
      child: Stack(
        children: [
          Positioned(
              bottom: 52,
              width: width,
              height: 300,
              child: Row(
                children: [
                  Expanded(
                      child: ListView.builder(
                          itemCount: clList.length,
                          itemBuilder: (BuildContext context, int index) {
                            return _buildClassItem(index, setState);
                          })),
                  VerticalDivider(
                    width: 2,
                    color: Colors.blueGrey,
                  ),
                  Expanded(
                      child: ListView.builder(
                          itemCount: stuList.length,
                          itemBuilder: (BuildContext context, int index) {
                            return _buildStuItem(index, setState);
                          })),
                ],
              )),
          Positioned(
              bottom: 50,
              width: width,
              child: Divider(
                color: Colors.grey,
                height: 1,
              )),
          Positioned(
            bottom: 0,
            height: 50,
            width: width,
            child: InkWell(
                onTap: () {
                  if (isCasting) {
                    Navigator.of(context).pop();
                    startCourse();
                  } else {
                    //todo: 分享
                    Navigator.of(context).pop();
                    startShare();
                  }
                },
                child: Center(
                  child: Text("确定"),
                )),
          ),
        ],
      ),
    );
  }
}
